package com.ayg.test.apitest.utils;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;

public class GsonUtil {

    //Gson将字符串转map时,int、long默认为double类型，这里进行转换
    public static Gson buildGson() {
         Gson gson = new GsonBuilder()
                .registerTypeAdapter(
                        new TypeToken<Map<String, Object>>() {
                        }.getType(),
                        new JsonDeserializer<Map<String, Object>>() {
                            @Override
                            public Map<String, Object> deserialize(
                                    JsonElement json, Type typeOfT,
                                    JsonDeserializationContext context) throws JsonParseException {
                                Map<String, Object> hashMap = new HashMap<String, Object>();
                                JsonObject jsonObject = null;
                                try {
                                    jsonObject = json.getAsJsonObject();
                                    Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                                    for (Map.Entry<String, JsonElement> entry : entrySet) {
                                        if(entry.getValue().isJsonArray() || entry.getValue().isJsonObject()){
                                            hashMap.put(entry.getKey(), entry.getValue());
                                        }else {
                                            //处理原本是字符串的不会出现2个双引号
                                            hashMap.put(entry.getKey(), entry.getValue().getAsString());
                                        }
                                    }
                                }catch (IllegalStateException e){
                                    e.printStackTrace();
                                }

                                return hashMap;
                            }
                        }).create();
        return gson;
    }
}
